<?php

namespace App\Http\Controllers\Mini\Circle;

use App\Http\Controllers\Controller;
use App\Models\Area;
use App\Models\HouseSell;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

/**
 * Class HouseSellController
 * @package App\Http\Controllers\Mini\Circle
 * 邻里圈 -- 房屋出售控制器
 */
class HouseSellController extends Controller
{
    private $user_id;

    public function __construct()
    {
        $id = auth('user')->id();

        $this->user_id = $id;
    }

    public function index(Request $request)
    {
        $type = $request->get('type');
        $house_type = $request->get('house_type', 'new');
        $where = [];
        $order = 'created_at';
        if ($house_type) {
            switch ($house_type) {
                case 'new':
                    $order = 'updated_at';
                    break;
                case 'all':
                    $order = 'id';
                    break;
                case 'hot':
                    $where[] = ['hot', '=', 1];
                    break;
                default:
                    return $this->error('house_type参数不允许');
            }
        }


        //只获取我发布的房源信息
        if ($type == 'my') {
            //需要先登录
            $user_id = $this->user_id;
            if (!$user_id) {
                return $this->error('请先登录');
            }
            $where[] = ['user_id', '=', $user_id];
        }

        $page = $request->get('page', 1);
        $limit = $request->get('limit', 20);
        $offset = ($page == 1) ? 0 : ($page - 1) * $limit;


        //发布时间倒序
        $data = HouseSell::query()->with('community:community_id,community_name')->select('id', 'title', 'money', 'image', 'house_type', 'community_id', 'username', 'room', 'hall', 'toilet', 'area', 'created_at')->where($where)->orderByDesc($order)->offset($offset)->limit($limit)->get();
        $response['data'] = $data;
        $response['count'] = HouseSell::query()->where($where)->count();
        $response['pages'] = ceil($response['count'] / $limit);
        return $this->success($response, '请求成功');
    }

    //发布出售信息
    public function store(Request $request)
    {
        $user_id = $this->user_id;
        if (!$user_id) {
            return $this->error('请先登录');
        }

        $data = $request->post();

        $res = $this->checkData($data);
        if ($res['code'] == 200) {
            $data['user_id'] = $user_id;
            HouseSell::query()->create($data);

            return $this->success();
        }
        return $this->error($res['msg'], $res['data']);
    }


    public function update(Request $request, $id)
    {
        $user_id = $this->user_id;
        if (!$user_id) {
            $this->error('请先登录');
        }

        $data = $request->post();

        $res = $this->checkData($data);

        if ($res['code'] == 200) {
            $data['user_id'] = $user_id;
            $result = HouseSell::query()->where('id', $id)->update($data);
            return $result ? $this->success() : $this->error();
        }

        return $this->error($res['msg']);
    }

    public function show($id)
    {
        //try捕获异常，查询使用firstOrFail方法，如果查询的内容不存在，会触发HTTP404的异常。
        try {
            $data = HouseSell::query()->with('community:community_id,community_address,city,community_name')->where('id', $id)->firstOrFail()->toArray();

            //计算大概每平米的单价
            $metreMoney = $data['money'] / $data['area'];

            $data['metre_money'] = $metreMoney;
            if (isset($data['community']['city'])) {
                $data['city'] = Area::query()->where('id', $data['community']['city'])->value('name');
            }
            $data['updated_at'] = $this->getTime($data['updated_at'], true);

        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }

        return $this->success($data);
    }

    public function destroy($id)
    {
        $user_id = $this->user_id;
        if (!$user_id) {
            return $this->error('请先登录');
        }

        $res = HouseSell::query()->where('id', $id)->delete();
        return $res ? $this->success([], '删除成功') : $this->error();
    }

    //检查数据是否合法
    private function checkData($data)
    {
        $validator = Validator::make($data, [
            'title' => 'required|max:255',
            'money' => 'required',
            'image' => 'required',
            'images' => 'required',
            'describe' => 'required',
            'room' => 'required|numeric',
            'hall' => 'required|numeric',
            'toilet' => 'required|numeric',
            'year' => 'required',
            'username' => 'required',
            'house_type' => 'required',
            'renovation' => 'required',
            'community_id' => 'required|numeric',
            'area' => 'required|numeric',
            'storey' => 'required',
            'direction' => 'required',
            'down_payments' => 'required|numeric',
            'call' => 'required',
            'phone' => 'required|regex:/^1[3456789][0-9]{9}$/'
        ]);

        if ($validator->fails()) {
            $errors = $validator->errors();
            return $this->error($errors->first());
        }

        return $this->success();
    }


    //出售房屋图片上传
    public function uploadImg(Request $request)
    {
        if ($this->user_id) {
            return $this->error('请先登录');
        }

        if ($request->hasFile('file')) {
            //获取图片
            $file = $request->file('file');
            //验证图片合法性
            $res = $this->checkFile($file, ['png', 'jpg', 'jpeg']);
            if ($res === true) {
                $path = $file->store('images/mini/circle/house_sell');
                if ($path) {
                    return $this->success(['path' => $path], '上传成功');
                }

            }
            return $this->error($res);
        }

        return $this->error('没有上传图片');
    }

    /**
     * 验证文件合法性
     * @param \Illuminate\Http\UploadedFile $file
     * @param array $extension
     * @param int $size 2m
     * @return bool|string
     */
    private function checkFile($file, $extension, $size = 2048000)
    {
        $fileExtension = strtolower($file->extension());
        if (!in_array($fileExtension, $extension)) {
            return '文件类型不允许';
        }

        $fileSize = $file->getSize();
        if ($fileSize >= $size) {
            return '图片大于2M';
        }

        return true;
    }

    /**
     * 判断几天前
     */
    private function getTime($targetTime, $time = 'Y-m-d')
    {
        $targetTime = strtotime($targetTime);
        // 今天最大时间
        $todayLast = strtotime(date('Y-m-d 23:59:59'));
        $agoTimeTrue = time() - $targetTime;
        $agoTime = $todayLast - $targetTime;
        $agoDay = floor($agoTime / 86400);

        if ($agoTimeTrue < 60) {
            $result = '刚刚';
        } elseif ($agoTimeTrue < 3600) {
            $result = (ceil($agoTimeTrue / 60)) . '分钟前';
        } elseif ($agoTimeTrue < 3600 * 12) {
            $result = $result = (ceil($agoTimeTrue / 3600)) . '小时前';
        } elseif ($agoDay >= 0 && $agoDay < 16) {
            $result = $result = $agoDay . '天前';
        } else {
            $format = date('Y') != date('Y', $targetTime) ? "Y-m-d H:i:s" : "$time";
            $result = date($format, $targetTime);
        }
        return $result;
    }
}
